Page({
  data: {
    // 游戏基础数据
    gameBoard: [], // 游戏板数据
    layers: 3, // 默认层数，从3层开始
    itemsPerLayer: 10, // 每层元素数量，从10个开始
    totalTypes: 6, // 图案种类数量，初始设为6种
    slotItems: [], // 收集槽中的图案
    maxSlotItems: 7, // 收集槽最大容量
    gameStatus: 'ready', // ready, playing, paused, over
    level: 1, // 当前关卡
    currentLevel: {
      layers: 3,
      itemsPerLayer: 10,
      totalTypes: 6
    }, // 当前关卡配置
    
    // 界面数据
    windowWidth: 0,
    windowHeight: 0,
    boardWidth: 0,
    boardHeight: 0,
    tileSize: 60, // 图块大小
    animating: false, // 是否正在播放动画
    
    // 更新SVG图片资源列表
    icons: [
      '/static/TwemojiTulip.svg',
      '/static/TwemojiTeddyBear.svg',
      '/static/TwemojiSunflower.svg',
      '/static/TwemojiRibbon.svg',
      '/static/TwemojiPigFace.svg',
      '/static/TwemojiMushroom.svg',
      '/static/TwemojiMango.svg',
      '/static/TwemojiLotionBottle.svg',
      '/static/FluentEmojiPanda.svg',
      '/static/EmojioneV1Rabbit.svg'
    ],
    
    // 道具图标
    bombIcon: '/static/bomb.png',
    hintIcon: '/static/hint.png',
    shuffleIcon: '/static/shuffle.png',
    heartIcon: '/static/heart.png',
    settingsIcon: '/static/settings.png',
    
    selectedTile: null,
    bombCount: 3,
    hintCount: 3,
    shuffleCount: 1,
    isSettingsVisible: false,
    isPaused: false,
    useBackupDisplay: false
  },

  onLoad() {
    // 获取设备信息
    const { windowWidth, windowHeight } = wx.getSystemInfoSync();
    
    // 计算游戏区域大小
    const boardWidth = windowWidth * 0.95;
    const boardHeight = windowHeight * 0.6;
    
    this.setData({
      windowWidth,
      windowHeight,
      boardWidth,
      boardHeight
    });
    
    // 初始化游戏 - 设置第一关
    this.setLevelConfig(1);
    this.initGame();
  },

  // 设置关卡配置
  setLevelConfig(level) {
    let levelConfig = {};
    
    // 根据关卡等级设置难度参数
    switch (level) {
      case 1:
        levelConfig = {
          layers: 3,
          itemsPerLayer: 10,
          totalTypes: 6
        };
        break;
      case 2:
        levelConfig = {
          layers: 4,
          itemsPerLayer: 15,
          totalTypes: 8
        };
        break;
      case 3:
        levelConfig = {
          layers: 5,
          itemsPerLayer: 20,
          totalTypes: 10
        };
        break;
      case 4:
        levelConfig = {
          layers: 6,
          itemsPerLayer: 25,
          totalTypes: 10
        };
        break;
      case 5:
        levelConfig = {
          layers: 7,
          itemsPerLayer: 30,
          totalTypes: 10
        };
        break;
      default:
        // 更高关卡或自定义配置
        levelConfig = {
          layers: 3 + level,
          itemsPerLayer: 10 + (level * 5),
          totalTypes: Math.min(10, 4 + level)
        };
    }
    
    this.setData({
      level,
      currentLevel: levelConfig,
      layers: levelConfig.layers,
      itemsPerLayer: levelConfig.itemsPerLayer,
      totalTypes: levelConfig.totalTypes
    });
  },

  initGame() {
    // 重置游戏状态
    this.setData({
      gameBoard: [],
      slotItems: [],
      gameStatus: 'ready'
    });
    
    // 生成游戏板
    this.generateGameBoard();
  },

  generateGameBoard() {
    const { layers, itemsPerLayer, totalTypes, icons } = this.data;
    const colors = ['#FF5252', '#FF9800', '#FFEB3B', '#4CAF50', '#2196F3', '#9C27B0', '#795548', '#607D8B', '#E91E63', '#00BCD4'];
    let gameBoard = [];
    
    // 设置固定的图块大小
    const tileSize = 60; // 固定60px
    
    // 更新图块大小
    this.setData({ tileSize });
    
    // 计算总图块数
    const totalTiles = layers * itemsPerLayer;
    
    // 确保总图块数是3的倍数
    if (totalTiles % 3 !== 0) {
      console.warn(`警告：总图块数 ${totalTiles} 不是3的倍数，可能导致无法完全消除的图块`);
    }
    
    // 生成确保每种类型都是3的倍数的分布
    let typeDistribution = this.generateBalancedTypeDistribution(totalTypes, totalTiles);
    
    // 准备每种类型的图块数组
    let tilesByType = [];
    for (let typeIndex = 0; typeIndex < totalTypes; typeIndex++) {
      const count = typeDistribution[typeIndex];
      for (let i = 0; i < count; i++) {
        tilesByType.push({
          type: typeIndex,
          color: colors[typeIndex % colors.length],
          icon: this.data.icons[typeIndex % this.data.icons.length]
        });
      }
    }
    
    // 随机打乱图块数组
    tilesByType = this.shuffleArray(tilesByType);
    
    // 生成各层
    let tileIndex = 0;
    for (let layer = 0; layer < layers; layer++) {
      let layerItems = [];
      
      // 为当前层生成元素
      for (let i = 0; i < itemsPerLayer && tileIndex < tilesByType.length; i++) {
        const tile = tilesByType[tileIndex++];
        
        // 随机位置，避免完全重叠
        const offsetX = Math.random() * 20 - 10;
        const offsetY = Math.random() * 20 - 10;
        
        // 确保图块不会超出边界
        const x = Math.max(0, Math.min(
          this.data.boardWidth - tileSize,
          Math.random() * (this.data.boardWidth - tileSize) + offsetX
        ));
        
        const y = Math.max(0, Math.min(
          this.data.boardHeight - tileSize,
          Math.random() * (this.data.boardHeight - tileSize) + offsetY
        ));
        
        layerItems.push({
          id: `${layer}-${i}`,
          type: tile.type,
          color: tile.color,
          icon: tile.icon,
          layer: layer,
          x: x,
          y: y,
          width: tileSize,
          height: tileSize,
          visible: true,
          unlocked: layer === 0,
          zIndex: layers - layer,
        });
      }
      
      gameBoard.push(layerItems);
    }
    
    this.setData({ gameBoard });
  },

  // 生成平衡的类型分布 - 确保每种类型都是3的倍数
  generateBalancedTypeDistribution(typeCount, totalItems) {
    // 确保总数是3的倍数
    totalItems = Math.floor(totalItems / 3) * 3;
    
    // 初始化分布数组
    let distribution = new Array(typeCount).fill(0);
    let itemsLeft = totalItems;
    
    // 首先确保每种类型至少有3个
    for (let i = 0; i < typeCount && itemsLeft >= 3; i++) {
      distribution[i] = 3;
      itemsLeft -= 3;
    }
    
    // 随机分配剩余的图块（按3的倍数）
    while (itemsLeft >= 3) {
      const typeIndex = Math.floor(Math.random() * typeCount);
      distribution[typeIndex] += 3;
      itemsLeft -= 3;
    }
    
    return distribution;
  },
  
  // Fisher-Yates 洗牌算法
  shuffleArray(array) {
    let currentIndex = array.length;
    let temporaryValue, randomIndex;
    
    // 当还有元素未洗牌时
    while (0 !== currentIndex) {
      // 选取剩余元素中的一个
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      
      // 交换当前元素和随机选中的元素
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    
    return array;
  },

  handleTileClick(e) {
    if (this.data.gameStatus !== 'playing' || this.data.animating) return;
    
    const { id } = e.currentTarget.dataset;
    const { gameBoard, slotItems, maxSlotItems } = this.data;
    
    // 找到点击的图块
    let clickedTile = null;
    let clickedLayerIndex = -1;
    let clickedTileIndex = -1;
    
    // 从上到下遍历层，找到第一个被点击的解锁图块
    for (let l = 0; l < gameBoard.length; l++) {
      for (let t = 0; t < gameBoard[l].length; t++) {
        const tile = gameBoard[l][t];
        if (tile.id === id && tile.visible && tile.unlocked) {
          clickedTile = tile;
          clickedLayerIndex = l;
          clickedTileIndex = t;
          break;
        }
      }
      if (clickedTile) break;
    }
    
    if (!clickedTile || !clickedTile.unlocked) return;
    
    // 检查收集槽是否已满
    if (slotItems.length >= maxSlotItems) {
      wx.showToast({
        title: '收集槽已满!',
        icon: 'none'
      });
      return;
    }

    // 复制当前游戏状态
    let newGameBoard = [...this.data.gameBoard];
    let newSlotItems = [...slotItems];
    
    // 更新图块状态
    newGameBoard[clickedLayerIndex][clickedTileIndex].visible = false;
    
    // 加入收集槽 - 确保图标路径也被复制
    newSlotItems.push({
      ...clickedTile,
      x: 0,
      y: 0,
    });
    
    // 检查是否有三个相同图案可以消除
    const type = clickedTile.type;
    const sameTypeCount = newSlotItems.filter(item => item.type === type).length;
    
    if (sameTypeCount >= 3) {
      // 消除同类型图案
      newSlotItems = newSlotItems.filter(item => item.type !== type);
            
            this.setData({
        gameBoard: newGameBoard,
        slotItems: newSlotItems,
        animating: true
      });
      
      
      setTimeout(() => {
        this.setData({ animating: false });
        // 更新底层图块的解锁状态
        this.updateTilesLockStatus();
        // 检查游戏是否结束
        this.checkGameStatus();
      }, 500);
      } else {
        this.setData({
        gameBoard: newGameBoard,
        slotItems: newSlotItems
      });
      
      // 更新底层图块的解锁状态
      this.updateTilesLockStatus();
      // 检查游戏是否结束
      this.checkGameStatus();
    }
  },

  updateTilesLockStatus() {
    const { gameBoard } = this.data;
    let newGameBoard = [...gameBoard];
    
    // 更新所有图块的解锁状态
    for (let l = 1; l < gameBoard.length; l++) {
      for (let t = 0; t < gameBoard[l].length; t++) {
        const tile = gameBoard[l][t];
        if (tile.visible && !tile.unlocked) {
          // 检查此图块是否被上层图块覆盖
          let isBlocked = false;
          
          // 检查所有上层图块
          for (let upperLayer = 0; upperLayer < l; upperLayer++) {
            for (let upperTile of gameBoard[upperLayer]) {
              if (upperTile.visible && this.tilesOverlap(tile, upperTile)) {
                isBlocked = true;
                break;
              }
            }
            if (isBlocked) break;
          }
          
          // 如果没有被覆盖，则解锁
          if (!isBlocked) {
            newGameBoard[l][t].unlocked = true;
          }
        }
      }
    }
    
    this.setData({ gameBoard: newGameBoard });
  },

  tilesOverlap(tile1, tile2) {
    const size = this.data.tileSize;
    return !(tile1.x + size < tile2.x || 
             tile1.x > tile2.x + size || 
             tile1.y + size < tile2.y || 
             tile1.y > tile2.y + size);
  },

  checkGameStatus() {
    const { gameBoard, slotItems, maxSlotItems, level } = this.data;
    
    // 检查是否所有图块都被清除
    let allCleared = true;
    for (let layer of gameBoard) {
      for (let tile of layer) {
        if (tile.visible) {
          allCleared = false;
          break;
        }
      }
      if (!allCleared) break;
    }
    
    if (allCleared) {
      // 游戏通关当前关卡
      if (level < 5) {
        // 还有下一关
        this.nextLevel();
      } else {
        // 通关全部关卡
        this.gameCompleted();
      }
      return;
    }
    
    // 检查是否收集槽已满且无法消除
    if (slotItems.length >= maxSlotItems) {
      // 检查是否有可以消除的组合
      let canEliminate = false;
      let typeCounts = {};
      
      for (let item of slotItems) {
        typeCounts[item.type] = (typeCounts[item.type] || 0) + 1;
      }
      
      for (let type in typeCounts) {
        if (typeCounts[type] >= 3) {
          canEliminate = true;
          break;
        }
      }
      
      if (!canEliminate) {
        // 游戏结束
        this.gameOver();
      }
    }
  },

  // 进入下一关
  nextLevel() {
    const nextLevel = this.data.level + 1;
    
    wx.showModal({
      title: '恭喜通关',
      content: `你已完成第${this.data.level}关，准备挑战第${nextLevel}关`,
      confirmText: '继续挑战',
      cancelText: '返回',
      success: (res) => {
        if (res.confirm) {
          // 设置下一关并重新初始化游戏
          this.setLevelConfig(nextLevel);
          this.initGame();
          this.setData({ gameStatus: 'playing' });
        } else {
          // 返回主页
          wx.navigateBack();
        }
      }
    });
  },

  // 完成所有关卡
  gameCompleted() {
    wx.showModal({
      title: '恭喜通关',
      content: '你已完成所有关卡！',
      confirmText: '重新开始',
      cancelText: '返回',
      success: (res) => {
        if (res.confirm) {
          // 重新开始第一关
          this.setLevelConfig(1);
          this.restartGame();
        } else {
          // 返回主页
          wx.navigateBack();
        }
      }
    });
  },

  // 游戏失败
  gameOver() {
    this.setData({ gameStatus: 'over' });
    
    wx.showModal({
      title: '游戏结束',
      content: `收集槽已满，第${this.data.level}关挑战失败!`,
      confirmText: '再次尝试',
      cancelText: '返回',
      success: (res) => {
        if (res.confirm) {
          // 重置当前关卡
          this.restartGame();
        } else {
          // 返回主页
          wx.navigateBack();
        }
      }
    });
  },

  startGame() {
    if (this.data.gameStatus === 'ready') {
      this.testImageLoad();
    }
  },

  pauseGame() {
    if (this.data.gameStatus === 'playing') {
      this.setData({ gameStatus: 'paused' });
    }
  },

  resumeGame() {
    if (this.data.gameStatus === 'paused') {
      this.setData({ gameStatus: 'playing' });
    }
  },

  backToHome() {
    wx.navigateBack();
  },

  onUnload() {
    // 移除计时器相关代码
  },

  // 添加清除所有选中状态的方法
  clearAllSelected(board) {
    for (let row of board) {
      for (let cell of row) {
        if (cell) {
          cell.selected = false;
          cell.matched = false;
        }
      }
    }
  },

  // 修改重新开始游戏方法
  restartGame() {
    // 重置游戏状态，但保持当前关卡设置
    this.setData({
      bombCount: 3,
      hintCount: 3,
      shuffleCount: 1,
      isSettingsVisible: false
    }, () => {
      // 在状态更新完成后再初始化游戏
      this.initGame();
      this.setData({ gameStatus: 'playing' });
    });
  },

  // 显示设置弹窗
  showSettings() {
    this.setData({
      isSettingsVisible: true,
      isPaused: true
    });
  },

  // 继续游戏
  continueGame() {
    this.setData({
      isSettingsVisible: false,
      isPaused: false
    }, () => {
      // 恢复游戏状态
      if (this.data.gameStatus === 'paused') {
        this.resumeGame();
      }
    });
  },

  // 修改广告结束后重新开始，移除时间相关逻辑
  restartAfterAd() {
    this.setData({
      isSettingsVisible: false,
      isPaused: false,
      bombCount: 3,
      hintCount: 3,
      shuffleCount: 1
    }, () => {
      this.initGame();
    });
  },

  // 测试加载图片
  testImageLoad() {
    // 设置状态
    this.setData({
      gameStatus: 'playing'
    });
  },

  // 处理图片加载错误
  handleImageError(e) {
    console.log('图片加载失败，使用备用显示', e);
    // 可以记录一个标志，表示图片加载失败，后续不再尝试加载
    this.setData({
      useBackupDisplay: true
    });
  },

  // 洗牌功能，重新打乱剩余的方块
  shuffleBoard() {
    // 检查洗牌次数
    if (this.data.shuffleCount <= 0) {
      wx.showToast({
        title: '洗牌次数不足',
        icon: 'none'
      });
      return;
    }

    // 按层收集所有未消除的方块
    let newGameBoard = JSON.parse(JSON.stringify(this.data.gameBoard));
    let layerTiles = [];
    
    // 先按层收集所有可见方块
    for (let layerIndex = 0; layerIndex < this.data.gameBoard.length; layerIndex++) {
      let tilesInThisLayer = [];
      
      // 收集当前层的所有可见方块
      for (let tileIndex = 0; tileIndex < this.data.gameBoard[layerIndex].length; tileIndex++) {
        const tile = this.data.gameBoard[layerIndex][tileIndex];
        if (tile.visible) {
          tilesInThisLayer.push({
            ...tile,
            originalIndex: tileIndex
          });
        }
      }
      
      // 保存此层的方块集合
      layerTiles.push(tilesInThisLayer);
    }
    
    // 如果没有剩余方块，直接返回
    let totalTiles = layerTiles.reduce((count, layer) => count + layer.length, 0);
    if (totalTiles === 0) {
      wx.showToast({
        title: '没有可洗牌的方块',
        icon: 'none'
      });
      return;
    }
    
    // 为每一层重新分配位置，但保持方块在原层
    for (let layerIndex = 0; layerIndex < layerTiles.length; layerIndex++) {
      let tilesInThisLayer = layerTiles[layerIndex];
      
      // 如果此层有方块，则重新打乱位置
      if (tilesInThisLayer.length > 0) {
        // 为每个方块分配新的随机位置
        for (let i = 0; i < tilesInThisLayer.length; i++) {
          const tile = tilesInThisLayer[i];
          const originalIndex = tile.originalIndex;
          
          // 随机位置，避免完全重叠
          const offsetX = Math.random() * 20 - 10;
          const offsetY = Math.random() * 20 - 10;
          
          // 确保图块不会超出边界
          const x = Math.max(0, Math.min(
            this.data.boardWidth - this.data.tileSize,
            Math.random() * (this.data.boardWidth - this.data.tileSize) + offsetX
          ));
          
          const y = Math.max(0, Math.min(
            this.data.boardHeight - this.data.tileSize,
            Math.random() * (this.data.boardHeight - this.data.tileSize) + offsetY
          ));
          
          // 更新方块位置，但保留其他属性
          newGameBoard[layerIndex][originalIndex] = {
            ...tile,
            x: x,
            y: y
          };
          
          // 移除辅助属性
          delete newGameBoard[layerIndex][originalIndex].originalIndex;
        }
      }
    }
    
    // 更新游戏数据
    this.setData({
      gameBoard: newGameBoard,
      shuffleCount: this.data.shuffleCount - 1,
      animating: true
    });
    
    setTimeout(() => {
      this.setData({ animating: false });
      // 更新底层图块的解锁状态
      this.updateTilesLockStatus();
      
      // 显示提示消息
      wx.showToast({
        title: '已重新洗牌',
        icon: 'success'
      });
    }, 500);
  },
}); 